// const moment = require("../../script/moment/moment");

var ns, toast;
var app = new Vue({
    el: '#app',
    data: {
        form: {
            timeMonth: '',
        },
        show_pro: true,
        show_fenlei: false,
        show_total: false,
        showsearchmonth: false,
        StartTime: '',
        EndTime: '',
        totalform: {},//营业总额
        orderform: {},//订单统计
        productform: {},//商品统计
        huiyuanform: {},//会员统计
        pageindex: 0,
        pagesize: 10,
        product_list: [],//商品销量排行
        chooseType: 1,
        nosort: false,


    },
    created() {
        const timeStr = '2022-08-01 16:17:14'
    },
    methods: {
        doSearch: function () {
            var that = this;
            that.StartTime = moment(that.StartTime).format('YYYY-MM-DD HH:mm:ss');
            that.EndTime = moment(that.EndTime).format('YYYY-MM-DD HH:mm:ss');
            that.get_total();
            that.load_lineChart();
            that.load_Circle();
            that.order_tongji();//订单统计
            that.product_tongji();//商品统计
            that.huiyuan_tongji();//会员统计
            that.product_xiaoliang();//商品销量

        },
        //营业额统计
        get_total: function () {
            var that = this;
            var option = {};
            option.StartTime = that.StartTime;
            option.EndTime = that.EndTime;
            option.action = 'overviewtotal';
            ns.post(option, function (succeed, data, err) {
                // console.log(JSON.stringify(data));
                if (succeed) {
                    that.totalform = data;
                } else {
                    api.toast({
                        msg: err,
                        duration: 2000,
                        location: 'bottom'
                    });
                }
            });

        },
        //订单统计
        order_tongji: function () {
            var that = this;
            ns.post({
                action: 'ordertotal'
            }, function (succeed, data, err) {
                if (succeed) {
                    that.orderform = data;
                } else {
                    api.toast({
                        msg: err,
                        duration: 2000,
                        location: 'bottom'
                    });
                }
            });
        },
        //商品数据
        product_tongji: function () {
            var that = this;
            ns.post({
                action: 'producttotal'
            }, function (succeed, data, err) {
                if (succeed) {
                    that.productform = data;
                } else {
                    api.toast({
                        msg: err,
                        duration: 2000,
                        location: 'bottom'
                    });
                }
            });
        },
        //会员统计
        huiyuan_tongji: function () {
            var that = this;
            ns.post({
                action: 'usertotal'
            }, function (succeed, data, err) {
                if (succeed) {
                    that.huiyuanform = data;
                    console.log(JSON.stringify(data));
                } else {
                    api.toast({
                        msg: err,
                        duration: 2000,
                        location: 'bottom'
                    });
                }
            });
        },
        // 商品销量
        product_xiaoliang: function () {
            var that = this;
            that.product_list = [];
            ns.post({
                action: 'orderitemrank',
                pageindex: that.pageindex,
                pagesize: that.pagesize,
            }, function (succeed, data, err) {
                if (succeed) {
                    that.product_list = data.list.rows;
                } else {
                    api.toast({
                        msg: err,
                        duration: 2000,
                        location: 'bottom'
                    });
                }
            });
        },



        // 调整库存
        updatenum: function () {
            var that = this;
            ns.openWin('product_update_num', '调整库存', {
                headerbg: 2
            });
        },

        //筛选菜单
        do_open_pro: function (type) {
            var that = this;
            console.log(type);
            if (type == 1) {
                that.chooseType = type;
                that.nosort=false;
            } else if (type == 2) {
                that.chooseType = type;

                setTimeout(function () {
                    that.load_Circle();
                }, 400);

            }
        },
        doSelectSearchParam: function () {
            var that = this;
            that.showsearchmonth = !that.showsearchmonth;
            setTimeout(() => {
                that.initPicker();
            }, 500);

        },
        //更多商品列表
        do_open_prolist: function () {
            ns.openWin('kanban_morepro', '更多商品');
        },
        //打开营业额详情
        do_openTotaldetail: function () {
            var that = this;
            that.show_total = !that.show_total;
        },
        //关闭营业额详情
        closebox: function () {
            var that = this;
            that.show_total = false;
        },
        //折线图表
        load_lineChart: function () {
            var that = this;
            var chartDom = document.getElementById('chartLine');
            var myChart = echarts.init(chartDom);
            var timedays = moment(that.form.timeMonth).daysInMonth();
            var xAxisData = [];
            for (let i = 1; i <= timedays; i++) {
                if (i % 5 == 0) {
                    xAxisData.push(i + "日")
                }
            }
            var d = moment(that.StartTime).format('D');
            var l = moment(that.EndTime).format('DD');
            xAxisData.splice(5, 1, l + '日');
            xAxisData.unshift(d + '日');
            const params = {
                action: 'turnovertotal',
                StartTime: that.StartTime,
                EndTime: that.EndTime,
            }
            var backData = []
            ns.post(params, function (succeed, data, err) {
                if (succeed) {
                    const newData = data.list || []
                    const md = moment(that.StartTime).format("YYYY-MM-")
                    for (let i = 0; i <= xAxisData.length - 1; i++) {
                        let startTime = 0
                        let entTime = 0
                        if (i == 0) {
                            startTime = md + "01 00:00:00"
                            entTime = md + "04 23:59:59"
                        }
                        if (i == 1) {
                            startTime = md + "05 00:00:00"
                            entTime = md + "09 23:59:59"
                        }
                        if (i == 2) {
                            startTime = md + "10 00:00:00"
                            entTime = md + "14 23:59:59"
                        }
                        if (i == 3) {
                            startTime = md + "15 00:00:00"
                            entTime = md + "19 23:59:59"
                        }
                        if (i == 4) {
                            startTime = md + "20 00:00:00"
                            entTime = md + "24 23:59:59"
                        }
                        if (i == 5) {
                            startTime = md + "25 00:00:00"
                            entTime = moment().endOf('months').endOf('day').format("YYYY-MM-DD HH:mm:ss")
                        }
                        const t = newData.filter(d => {
                            return moment(d.AddTime).unix() >= moment(startTime).unix() && moment(d.AddTime).unix() < moment(entTime).unix()
                        })
                        const num = t.reduce((total, item) => {
                            return total + (item.LastTotalCost || 0);
                        }, 0)
                        backData.push(num)
                    }
                    var option;
                    option = {
                        tooltip: {
                            trigger: 'axis'
                        },
                        xAxis: {
                            type: 'category',
                            boundaryGap: true,//坐标轴两边留白
                            data: xAxisData,
                        },
                        yAxis: {
                            type: 'value',
                        },
                        series: [
                            {
                                data: backData.length < 0 ? [0, 0, 0, 0, 0, 0, 0] : backData,
                                markPoint: {
                                    data: [
                                        { type: 'max', name: 'Max' },
                                        { type: 'min', name: 'Min' }
                                    ]
                                },
                                type: 'line',
                                smooth: true
                            }
                        ]
                    };
                    option && myChart.setOption(option);
                }
            })
        },
        // 获取图表数据
        getEchartData: function () {
            const that = this;



        },
        //环形图表
        load_Circle: function () {
            var that = this;
            var chartDom = document.getElementById('chartCirle');
            var myChart = echarts.init(chartDom);
            var sortdata = [];

            const params = {
                action: 'orderitemcatetotal',
                StartTime: that.StartTime,
                EndTime: that.EndTime,
            }
            ns.post(params, function (succeed, data, err) {
                if (succeed) {
                    var total=data.total.Quantity;
                    // console.log(JSON.stringify(data.total.Quantity));
                    if (data.list.length > 0) {
                        var sortlist = data.list;
                        console.log(JSON.stringify(sortlist));
                        for (var i = 0; i < sortlist.length; i++) {
                            var item = {
                                value: sortlist[i].Quantity,
                                name: sortlist[i].ProductCategoryName
                            }
                            sortdata.push(item);
                        }
                        var option;
                        option = {
                            tooltip: {
                                trigger: 'item'
                            },
                            title: {
                                text: [
                                    '{name|商品销量}',
                                    '{totalnum|'+total+'}'
                                ].join('\n'),
                                textStyle: {
                                    rich: {
                                        name: {
                                            fontSize: 16,
                                            color: '#999',
                                            lineHeight: 36,
                                        },
                                        totalnum: {
                                            fontSize: 24,
                                            color: '#000',
                                            fontWeight: 'bold',
                                        }
                                    }
                                },
                                left: 'center',
                                top: 'center'
                            },
                            series: [
                                {
                                    name: '商品分类',
                                    type: 'pie',
                                    radius: ['40%', '70%'],
                                    itemStyle: {
                                        borderRadius: 10,
                                        borderColor: '#fff',
                                        borderWidth: 2
                                    },
                                    data: sortdata.length < 0 ? [0, 0, 0, 0, 0, 0, 0] : sortdata,
                                }
                            ]
                        };
                        option && myChart.setOption(option);

                    }else {
                        that.nosort=true;
                    }

                } 
            });


        },
        initPicker: function () {
            var _this = this;
            (function ($, doc) {
                $.init();
                $.ready(function () {
                    //月份
                    var btn = document.querySelector('#datemonth');
                    btn.addEventListener('tap', function () {
                        var _self = this;
                        if (_self.picker) {
                            _self.picker.show(function (rs) {
                                _this.form.timeMonth = rs.value;
                                _this.StartTime = moment(_this.form.timeMonth).startOf('month');
                                _this.EndTime = moment(_this.form.timeMonth).endOf('month');
                                _self.picker.dispose();
                                _self.picker = null;
                            });
                        } else {
                            var optionsJson = this.getAttribute('data-options') || '{}';
                            var options = JSON.parse(optionsJson);
                            var id = this.getAttribute('id');
                            _self.picker = new $.DtPicker(options);
                            _self.picker.show(function (rs) {
                                var timer = setTimeout(function () {
                                    clearTimeout(timer);
                                    _this.form.timeMonth = rs.value;
                                    _this.StartTime = moment(_this.form.timeMonth).startOf('month');
                                    _this.EndTime = moment(_this.form.timeMonth).endOf('month');
                                    // _this.ChangeTime(_this.form.timeMonth);
                                    _this.doSearch();
                                }, 300);
                                _self.picker.dispose();
                                _self.picker = null;
                            });
                        }
                    }, false);
                });
            })(mui, document);
        },

        // ChangeTime:function(day){
        //     var that=this;
        //     var Monthtime = dateRangeUtil.getMonthTime(day);
        //     that.StartTime = dateRangeUtil.getMonthTime(Monthtime[0]);
        //     that.EndTime = dateRangeUtil.getMonthTime(Monthtime[1]);
        //     console.log(JSON.stringify(that.StartTime));
        //     console.log(JSON.stringify(that.EndTime));
        // },

        set_status_bar: function () {
            var that = this;
            api.setStatusBarStyle({
                style: 'dark',
                color: 'transparent'
            });
        },

    },
});

apiready = function () {
    api.parseTapmode();
    app.set_status_bar();
    ns = window.Foresight.Util;
    var nowDate = new Date();
    var Y = nowDate.getFullYear();
    var M = nowDate.getMonth() + 1 < 10 ? '0' + (nowDate.getMonth() + 1) : nowDate.getMonth() + 1;
    app.form.timeMonth = moment().format('YYYY-MM');
    app.StartTime = moment(app.form.timeMonth).startOf('month');
    app.EndTime = moment(app.form.timeMonth).endOf('month');
    app.doSearch();


    // api.addEventListener({
    //     name: 'onlogin'
    // }, function(ret, err) {
    //     app.get_data();
    // });
    // api.addEventListener({
    //     name: 'shopmsgevent'
    // }, function(ret, err){
    //       app.get_data();
    // });
    // app.initPicker();
    // app.load_lineChart();
    // app.load_Circle();
    api.addEventListener({
        name: 'do_open_search'
    }, function (ret, err) {
        ns.openWin('search_frm', '搜索');
    });
    api.addEventListener({
        name: 'do_open_fenlei'
    }, function (ret, err) {
        ns.openWin('product_sort', '商品分类');
    });

    // var top_tab = 　$api.byId('tab')
    // var body_h = api.winHeight;
    // var top_tab_h = $api.offset(top_tab).h;
    // var header_h = api.pageParam.header_h;
    // var status = api.pageParam.status;

}
